package com.example.demo.controller;

import com.example.demo.pojo.Response;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.EncryptUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class UserController extends EncryptUtils {

    @Autowired
    private UserService userService;

    @Operation(summary = "用户注册")
    @PostMapping(value = "/register")
    @ApiResponse(responseCode = "200", description = "注册成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> userRegister(@RequestParam("email") String email,
                                                       @RequestParam("password") String password) {
        Response<User> response = new Response<>();

        try {
            if (userService.isUserExist(email) != null) {
                System.out.println(userService.isUserExist(email));
                response.setCode(400);
                response.setMessage("用户已存在");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
            } else {
                User user = userService.UserRegister(email, encrypt(password));
                if (user == null) {
                    response.setCode(500);
                    response.setMessage("注册失败，服务器异常");
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
                }
                response.setUser(user);
                response.setCode(200);
                response.setMessage("注册成功");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    @ApiResponse(responseCode = "200", description = "登录成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> userLogin(@RequestParam("email") String email,
                                                    @RequestParam("password") String password,
                                                    @Parameter(description = "是否为管理员登录") @RequestParam("isManager") Boolean isManager) {
        Response<User> response = new Response<>();
        try {
            if (!isManager) {
                User user = userService.isUserExist(email);
                if (user == null) {
                    response.setCode(404);
                    response.setMessage("用户未找到");
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
                } else {
                    if(!user.getUser_state()){
                        response.setCode(401);
                        response.setMessage("用户已冻结");
                        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
                    }
                    User loginuser = userService.UserLogin(email, encrypt(password));
                    System.out.println("loginuser: " + loginuser);
                    if (loginuser == null) {
                        response.setCode(401);
                        response.setMessage("密码错误");
                        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
                    }
                    response.setCode(200);
                    response.setMessage("用户登录成功");
                    response.setUser(loginuser);
                    return ResponseEntity.ok(response);
                }
            } else {
                if (Objects.equals(email, "admin@qq.com") && Objects.equals(password, "123456")) {
                    User loginuser = new User();
                    loginuser.setEmail(email);
                    loginuser.setPassword(password);
                    response.setCode(200);
                    response.setMessage("管理员登录成功");
                    response.setUser(loginuser);
                    return ResponseEntity.ok(response);
                }

                if(!Objects.equals(email, "admin@qq.com")){
                    response.setMessage("你不是管理员");
                } else if (!Objects.equals(password, "123456")){
                    response.setMessage("密码错误");
                }
                response.setCode(401);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);

            }
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "查找用户ById")
    @GetMapping("/find-byid")
    @ApiResponse(responseCode = "200", description = "查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> findById(@RequestParam("user_id") Integer user_id) {
        System.out.println("Received user_id: " + user_id);
        Response<User> response = new Response<>();
        try {
            User user = userService.findUserById(user_id);
            System.out.println("Query result: " + user);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setUser(user);
            response.setMessage("查找成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "查找所有用户")
    @GetMapping("/find-all")
    @ApiResponse(responseCode = "200", description = "查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> findAll() {
        Response<User> response = new Response<>();
        try {
            List<User> list = userService.findAllUser();
            if (!list.isEmpty()) {
                response.setCode(200);
                response.setMessage("查找成功");
                response.setList(list);
                return ResponseEntity.ok(response);
            } else {
                response.setCode(404);
                response.setMessage("用户列表为空");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "修改密码")
    @PutMapping("/update/password")
    @ApiResponse(responseCode = "200", description = "修改成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> updatePassword(@Parameter(description = "用户id") @RequestParam("user_id") Integer user_id,
                                                         @Parameter(description = "原密码") @RequestParam("password") String password,
                                                         @Parameter(description = "新密码") @RequestParam("newpassword") String newpassword) {
        Response<User> response = new Response<>();
        try {
            System.out.println("Received user_id: " + user_id);
            System.out.println("Received password: " + password);
            System.out.println("Received newpassword: " + newpassword);

            if (Objects.equals(password, newpassword)) {
                response.setCode(401);
                response.setMessage("新密码不能与原密码相同");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }

            User user = userService.findUserById(user_id);
            System.out.println("user: " + user);

            if (Objects.equals(user.getPassword(), encrypt(password))) {
                User newuser = userService.updatePassword(user_id, encrypt(newpassword));
                if (newuser == null) {
                    response.setCode(404);
                    response.setMessage("用户未找到");
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
                }
                response.setCode(200);
                response.setMessage("密码更新成功");
                response.setUser(newuser);
                return ResponseEntity.ok(response);
            } else {
                response.setCode(401);
                response.setMessage("原密码错误");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "添加地址")
    @PutMapping("/add/address")
    @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> addAddress(@RequestParam("user_id") Integer user_id,
                                                     @RequestParam("address") String address) {
        Response<User> response = new Response<>();
        try {
            User user = userService.updateAddress(user_id, address);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setMessage("地址更新成功");
            response.setUser(user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "修改地址")
    @PutMapping("/update/address")
    @ApiResponse(responseCode = "200", description = "修改成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> updateAddress(@RequestParam("user_id") Integer user_id,
                                                        @RequestParam("address") String address) {
        Response<User> response = new Response<>();
        try {
            User user = userService.updateAddress(user_id, address);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setMessage("地址更新成功");
            response.setUser(user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }


    @Operation(summary = "删除地址")
    @DeleteMapping("/delete/address")
    @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> deleteAddress(@RequestParam("user_id") Integer user_id) {
        Response<User> response = new Response<>();
        try {
            User user = userService.findUserById(user_id);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            user.setAddress("");
            userService.updateAddress(user_id, "");
            response.setCode(200);
            response.setMessage("地址删除成功");
            response.setUser(user);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "修改用户名")
    @PutMapping("/update/username")
    @ApiResponse(responseCode = "200", description = "修改成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> updateUsername(@RequestParam("user_id") Integer user_id,
                                                         @RequestParam("username") String username) {
        Response<User> response = new Response<>();
        try {
            User user = userService.findUserById(user_id);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            } else {
                if(Objects.equals(user.getUsername(), username)) {
                    response.setCode(401);
                    response.setMessage("新用户名与原用户名相同");
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
                }
            }
            User newuser = userService.updateUsername(user_id, username);
            response.setCode(200);
            response.setMessage("用户名更新成功");
            response.setUser(newuser);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "修改头像")
    @PutMapping("/update/avatar")
    @ApiResponse(responseCode = "200", description = "修改成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> updateAvatar(@RequestParam("user_id") Integer user_id,
                                                       @RequestParam("avatar") MultipartFile avatar) {
        FileController fileController = new FileController();
        ResponseEntity<String> url = fileController.uploadFile(avatar);
        System.out.println(url.getBody());
        Response<User> response = new Response<>();
        try {
            User user = userService.findUserById(user_id);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
//            删除上传的图片
            if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                System.out.println(user.getAvatar());
                String avatarPath = user.getAvatar();
                if (avatarPath.startsWith("/")) {
                    avatarPath = avatarPath.substring(1);
                }
                fileController.deleteFile(avatarPath);
            }

            User newUser = userService.updateAvatar(user_id, url.getBody());
            response.setCode(200);
            response.setMessage("头像更新成功");
            response.setUser(newUser);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "查找用户")
    @GetMapping("/manager/find")
    @ApiResponse(responseCode = "200", description = "查找成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> findUser(@Parameter(description = "搜索内容") @RequestParam("SearchContent") String SearchContent) {
        Response<User> response = new Response<>();
        try {
            List<User> userList = userService.findUserSearch(SearchContent);
            if (userList.isEmpty()) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            response.setCode(200);
            response.setMessage("搜索成功");
            response.setList(userList);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "修改用户状态")
    @PutMapping("/update/status")
    @ApiResponse(responseCode = "200", description = "修改成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> updateStatus(@RequestParam("user_id") Integer user_id,
                                                       @RequestParam("status") Boolean status) {
        Response<User> response = new Response<>();
        try {
            User user = userService.findUserById(user_id);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            User newuser = userService.updateStatus(user_id, status);
            response.setCode(200);
            response.setMessage("用户状态更新成功");
            response.setUser(newuser);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @Operation(summary = "用户注销")
    @DeleteMapping("/delete")
    @ApiResponse(responseCode = "200", description = "注销成功", content = @Content(mediaType = "application/json"))
    public ResponseEntity<Response<User>> deleteUser(@RequestParam("user_id") Integer user_id) {
        Response<User> response = new Response<>();
        try {
            User user = userService.findUserById(user_id);
            if (user == null) {
                response.setCode(404);
                response.setMessage("用户未找到");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            FileController fileController = new FileController();
            if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                System.out.println(user.getAvatar());
                String avatarPath = user.getAvatar();
                if (avatarPath.startsWith("/")) {
                    avatarPath = avatarPath.substring(1);
                }
                fileController.deleteFile(avatarPath);
            }

            userService.deleteUser(user_id);
            response.setCode(200);
            response.setMessage("用户注销成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.setCode(500);
            response.setMessage("服务器错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

}